package com.ebpm.designer.menu
{
	import com.ebpm.designer.NodeContainer;
	import com.ebpm.designer.WF;
	
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.net.FileReference;
	
	public class SaveMenu extends MenuItem
	{
		public function SaveMenu(iconImage:Class, x:Number=0, y:Number=0)
		{
			super(iconImage, x, y);
		}
		
		override public function _click(event:MouseEvent):void
		{
			SaveMenu.saveFile();
		}
		
		public static function saveFile():void {
			if(WF.wp.nodeContainers == null || WF.wp.nodeContainers.length == 0) {
				return ;
			}
			var data:String = buildXmlData();
			var fr:FileReference = new FileReference();
			fr.addEventListener(Event.COMPLETE, onFileCompleteHandler);
			fr.addEventListener(Event.CANCEL, onFileCancelHandler);
			fr.save(data, "define.xml");
		}
		
		//文件【保存】或【取消】后，必须将焦点指到wp，键盘事件才会停留在wp上
		private static function onFileCancelHandler(event:Event):void
		{
			WF.wp.setFocus();
		}
		private static function onFileCompleteHandler(event:Event):void {
			WF.wp.setFocus();
		}
		
		public static function buildXmlData():String {
			var processKey:String = null;
			var processDesc:String = null;
			if(WF.wp.startEvent != null) {
				processKey = WF.wp.startEvent.nodeContainer.variable.processKey;
				processDesc = WF.wp.startEvent.nodeContainer.variable.processDesc;
			}
			WF.xmlDefinitionsData = "<Definitions key=\"" + processKey + "\" desc=\"" + processDesc + "\">\n";
			WF.xmlPositionData = "\n\n<Position>\n";
			WF.xmlTaskJson = "\n\n<TaskJson>\n<![CDATA[\n[";
			WF.xmlLineJson = "\n\n<LineJson>\n<![CDATA[\n[";
			
			for(var i:Number=0; i<WF.wp.nodeContainers.length; i++) {
				var temp:NodeContainer = WF.wp.nodeContainers.getItemAt(i) as NodeContainer;
				if(!temp.mission.buildTaskXml()) return null;
				if(!temp.buildLineXml()) return null;
			}
			
			WF.xmlDefinitionsData += "</Definitions>";
			WF.xmlPositionData += "</Position>";
			WF.xmlTaskJson = WF.xmlTaskJson.substring(0, WF.xmlTaskJson.length-1);
			WF.xmlTaskJson += "]\n]]>\n</TaskJson>";
			WF.xmlLineJson = WF.xmlLineJson.substring(0, WF.xmlLineJson.length-1);
			WF.xmlLineJson += "]\n]]>\n</LineJson>";
			return WF.xmlDefinitionsData + WF.xmlPositionData + WF.xmlTaskJson + WF.xmlLineJson;
		}
		
		
		override public function getIconImage() : Class {
			return WF.MenuSave;
		}
		
		override public function getIconImageOver() :Class {
			return WF.MenuSave1;
		}
		
		
		
		
		
		
		
		
		
		
	}
}